﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;

namespace ServiceStack.OrmLite
{
    public static class ExpressionExtension
    {
        public static List<List<object>> IfInSplitIds(this IEnumerable ids, int inMaxCount = 1000)
        {
            List<List<object>> lst_lst = new List<List<object>>();

            List<object> idValues = new List<object>();

            if (idValues != null)
            {
                if (ids is object[] arr)
                {
                    idValues = new List<object>(arr);
                }
                else if (ids is IEnumerable<object> objs)
                {
                    idValues = new List<object>(objs);
                }
                else if (ids is IList lst)
                {
                    idValues = new List<object>(lst.Cast<object>());
                }
                else
                {
                    foreach (var item in ids)
                    {
                        idValues.Add(item);
                    }
                }
            }

            if (idValues != null && idValues.Count > inMaxCount)
            {
                int pageCount = idValues.Count % inMaxCount > 0 ? (idValues.Count / inMaxCount + 1) : idValues.Count / inMaxCount;

                for (int j = 0; j < pageCount; j++)
                {
                    var items = idValues.Skip(j * inMaxCount).Take(inMaxCount).ToList();
                    lst_lst.Add(items);
                }
            }
            else
            {
                lst_lst.Add(idValues);
            }

            return lst_lst;
        }


        /// <summary>
        /// 获取 expr 的 list 集合
        /// </summary>
        /// <param name="expr"></param>
        /// <returns></returns>
        public static object EnumerableObject(this Expression expr)
        {
            MemberExpression memExpr = null;
            // contains
            memExpr = (((expr as LambdaExpression)?.Body as MethodCallExpression)?.Object as MemberExpression);

            // !contains
            if (memExpr == null)
            {
                memExpr = ((((expr as LambdaExpression)?.Body as UnaryExpression)?.Operand as MethodCallExpression)?.Object as MemberExpression);
            }

            if (memExpr == null)
            {
                return null;
            }

            object val;

            var field = memExpr?.Member as FieldInfo;

            if (field != null)
            {
                val = field.GetValue(((ConstantExpression)memExpr.Expression).Value);
            }
            else
            {
                val = ((PropertyInfo)memExpr.Member).GetValue(((ConstantExpression)memExpr.Expression).Value, null);
            }
            return val;
        }


        /// <summary>
        /// 根据集合 分割成功 多个 expr 表达式
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="where"></param>
        /// <param name="inMaxCount"></param>
        /// <returns></returns>
        public static List<Expression<Func<T, bool>>> IfInSplitExpr<T>(this Expression<Func<T, bool>> where, int inMaxCount = 1000)
        {
            List<Expression<Func<T, bool>>> lstExpr = new List<Expression<Func<T, bool>>>();

            List<object> values = null;
            IEnumerable<object> asList = where?.EnumerableObject() as IEnumerable<object>;
            if (asList != null)
            {
                values = new List<object>(asList);
            }

            if (asList == null || (asList != null && values.Count <= inMaxCount))
            {
                lstExpr.Add(where);
                return lstExpr;
            }

            MethodCallExpression method_lmd = null;
            // contains
            method_lmd = ((where as LambdaExpression)?.Body as MethodCallExpression);

            // !contains
            if (method_lmd == null)
            {
                method_lmd = ((where as LambdaExpression)?.Body as UnaryExpression)?.Operand as MethodCallExpression;
            }

            var prop_lmd = method_lmd?.Arguments?.FirstOrDefault() as MemberExpression;

            if (values != null && values.Count > inMaxCount && method_lmd != null && method_lmd.Method.Name == "Contains")
            {
                int pageCount = values.Count % inMaxCount > 0 ? (values.Count / inMaxCount + 1) : values.Count / inMaxCount;

                for (int j = 0; j < pageCount; j++)
                {
                    var items = values.Skip(j * inMaxCount).Take(inMaxCount).ToList();

                    var pExpr = Expression.Parameter(typeof(T), "p");

                    var cstExpr = Expression.Constant(items);

                    var memExpr = Expression.Property(pExpr, prop_lmd.Member.Name);


                    MethodCallExpression containsExpr = Expression.Call(cstExpr
                        , "Contains", new Type[] { }, memExpr);
                    ;

                    Expression<Func<T, bool>> expr = Expression.Lambda<Func<T, bool>>(containsExpr, pExpr);

                    lstExpr.Add(expr);
                }
            }
            else
            {
                lstExpr.Add(where);
            }
            return lstExpr;
        }
    }
}


